package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignClient;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    //配置mvc后无需以下方法
//    @GetMapping("/index.html")
//    public String loginPage(){
//        return "login";
//    }
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Resource
    private MemberFeignClient memberFeignClient;

    @ResponseBody
    @PostMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        String redisCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (redisCode != null) {
            String[] redisCodeSplit = redisCode.split("_");
            if (Long.parseLong(redisCodeSplit[1]) - System.currentTimeMillis() < 60000) {
                return R.error(BizCodeEnum.VAILD_SMSCODE_EXCEPTION.getCode(), BizCodeEnum.VAILD_SMSCODE_EXCEPTION.getMsg());
            }
        }
        //加上系统时间，防止60s内重复发送
        String code = UUID.randomUUID().toString().substring(0, 5);
        String subCode = code + "_" + System.currentTimeMillis();
        //Todo，调用第三方短信接口发送验证码
        //验证码的再次校验，key:手机号，value:验证码
        redisTemplate.opsForValue().set(AuthConstant.SMS_CODE_CACHE_PREFIX + phone, subCode, 10, TimeUnit.MINUTES);
        return R.ok().put("code", code);
    }

    @PostMapping("/register")
    public String register(@Valid UserRegisterVo userRegisterVo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> map = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", map);
            //校验注册，有错误回到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        String code = userRegisterVo.getCode();
        String redisCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());
        if (redisCode != null) {
            if (redisCode.split("_")[0].equals(code)) {
                redisTemplate.delete(AuthConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());
                //验证码通过，进行注册
                R r = memberFeignClient.register(userRegisterVo);
                if (r.getCode() == 0) {
                    //成功
                    return "redirect:/login.html";
                } else {
                    Map<String, String> map = new HashMap<>();
                    map.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", map);
                    //校验注册，有错误回到注册页
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                Map<String, String> map = new HashMap<>();
                map.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", map);
                //校验注册，有错误回到注册页
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            Map<String, String> map = new HashMap<>();
            map.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", map);
            //校验注册，有错误回到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @PostMapping("login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {
        //调用远程登录
        R r = memberFeignClient.login(vo);
        if (r.getCode() == 0) {
            //成功，则放入session
            MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthConstant.LOGIN_USER, data);
            return "redirect:http://gulimall.com";
        } else {
            Map<String, String> map = new HashMap<>();
            map.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", map);
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
